//
//  FamousPersonDetailViewController.m
//  ShangHaiTuJI
//
//  Created by xiaoxiangtuji on 2017/8/11.
//  Copyright © 2017年 xiaoxiangtuji. All rights reserved.
//
#import "FamousPersonDetailViewController.h"
#import "DetailAuthorIntroduceCell.h"
#import "DetailAuthorParticularsIntroduceCell.h"
#import "DetailAuthorHeaderCell.h"
#import "DetailAuthorBottomCell.h"
#import "CommentDetailViewController.h"
#import "XLVideoPlayer.h"
#import "BigIntellgientModel.h"
#import "OpusListModel.h"
#import "UIImageView+WebCache.h"
#import "UITextField+LXDAdjust.h"
#import "MusicManager.h"
#import <AVFoundation/AVFoundation.h>
#import "FamousListCell.h"
#import "FamousListVideoViewController.h"
#import <WebKit/WebKit.h>
@interface FamousPersonDetailViewController ()<UITableViewDelegate,UITableViewDataSource,WKUIDelegate,WKNavigationDelegate,UIWebViewDelegate,UITextFieldDelegate>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)UIWebView *webView;
//@property(nonatomic,strong)WKWebView *webView;
@property(nonatomic,strong)UIImageView *imageView;
@property(nonatomic,strong)UIButton *playOrPauseBtn;
@property(nonatomic,strong)UISlider *slider;
@property(nonatomic,strong)UILabel *CurrentTimeLabel;
@property(nonatomic,strong)UILabel *totlaLabel;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,strong)UIView *headerView;
@property(nonatomic,strong)NSMutableArray *listArray;
@property(nonatomic,strong)MBProgressHUD *hud;
@property(nonatomic,strong)NSDictionary *param;
@property(nonatomic,copy)NSString *senImagePath;
@end

@implementation FamousPersonDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //    [self getDetailVcDataAccordingId:self.inforId];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [self.listArray removeAllObjects];
    [self createAvPlayerView];
    if (self.authotId) {
        [self getPersonDetailVcDataAccordingId:self.authotId];
    }else{
        [self getPersonDetailVcDataAccordingId:self.inforId];
    }
    self.tabBarController.tabBar.hidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = NO;
}
//-(void)chooseGoRefreshPage:(NSNotification *)infor{
//    [self getPersonDetailVcDataAccordingId:infor.userInfo[@"FILEID"]];
//}
#pragma mark -创建音频播放器
-(void)createAvPlayerView{
    /*******************设置头部视图的播放音频的页面******************************/
    _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, scaleTopAndBottom(300))];
    _headerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_headerView];
    _imageView = [[UIImageView alloc] init];
    _imageView.backgroundColor = [UIColor redColor];
    [_headerView addSubview:_imageView];
    [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(_headerView);
        make.height.mas_equalTo(scaleTopAndBottom(210));
    }];
    _slider = [[UISlider alloc] init];
    [_slider addTarget:self action:@selector(progressAct:) forControlEvents:UIControlEventValueChanged];
    [_headerView addSubview:_slider];
    [_slider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_headerView);
        make.top.equalTo(_imageView.mas_bottom);
        make.height.mas_equalTo(scaleTopAndBottom(3));
        
    }];
    _CurrentTimeLabel = [[UILabel alloc] init];
    _CurrentTimeLabel.textAlignment = NSTextAlignmentLeft;
    _CurrentTimeLabel.text = @"00:00";
    [_headerView addSubview:_CurrentTimeLabel];
    [_CurrentTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_headerView);
        make.top.equalTo(_slider.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(scaleLeftAndRight(100), scaleTopAndBottom(10)));
    }];
    _totlaLabel = [[UILabel alloc] init];
    _totlaLabel.textAlignment = NSTextAlignmentRight;
    [_headerView addSubview:_totlaLabel];
    [_totlaLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_headerView);
        make.top.equalTo(_slider.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(scaleLeftAndRight(100), scaleTopAndBottom(10)));
    }];
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_headerView addSubview:leftBtn];
    [leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_headerView.mas_left).offset(scaleLeftAndRight(100));
        make.top.equalTo(_slider.mas_bottom).offset(scaleTopAndBottom(35));
        make.size.mas_equalTo(CGSizeMake(scaleLeftAndRight(20), scaleLeftAndRight(20)));
    }];
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_headerView addSubview:rightBtn];
    [rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_headerView.mas_right).offset(scaleLeftAndRight(-100));
        make.top.equalTo(_slider.mas_bottom).offset(scaleTopAndBottom(35));
        make.size.mas_equalTo(CGSizeMake(scaleLeftAndRight(20), scaleLeftAndRight(20)));
    }];
    _playOrPauseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_headerView addSubview:_playOrPauseBtn];
    [_playOrPauseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_headerView.mas_centerX);
        make.top.equalTo(_slider.mas_bottom).offset(scaleTopAndBottom(20));
        make.size.mas_equalTo(CGSizeMake(scaleLeftAndRight(50), scaleLeftAndRight(50)));
    }];
    UIButton *listBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [listBtn addTarget:self action:@selector(ListCellChoose:) forControlEvents:UIControlEventTouchUpInside];
    listBtn.backgroundColor = [UIColor redColor];
    [_headerView addSubview:listBtn];
    [listBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(scaleLeftAndRight(30), scaleTopAndBottom(40)));
        make.left.equalTo(_headerView.mas_left).offset(scaleLeftAndRight(20));
        make.top.equalTo(_slider.mas_bottom).offset(scaleTopAndBottom(20));
    }];
    leftBtn.tag = 1000;
    rightBtn.tag = 1001;
    _playOrPauseBtn.tag = 1002;
    [leftBtn addTarget:self action:@selector(MusicRuntimeChoose:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn addTarget:self action:@selector(MusicRuntimeChoose:) forControlEvents:UIControlEventTouchUpInside];
    [_playOrPauseBtn addTarget:self action:@selector(MusicRuntimeChoose:) forControlEvents:UIControlEventTouchUpInside];
    _slider.backgroundColor = [UIColor whiteColor];
    [_playOrPauseBtn setBackgroundImage:[UIImage imageNamed:@"playplay"] forState:UIControlStateNormal];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"leftleft"] forState:UIControlStateNormal];
    [rightBtn setBackgroundImage:[UIImage imageNamed:@"rightright"] forState:UIControlStateNormal];
    _totlaLabel.backgroundColor = [UIColor clearColor];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAct) userInfo:nil repeats:YES];

    
}
-(void)progressAct:(id)sender{
    [[MusicManager shareInfo] playerProgressWithProgressFloat:((UISlider*)sender).value];
}

- (void)timerAct{
    if ([MusicManager shareInfo].player.currentTime.timescale == 0 || [MusicManager shareInfo].player.currentItem.duration.timescale == 0) {
        return;
    }
    // 获得音乐总时长
    long long int totalTime = [MusicManager shareInfo].player.currentItem.duration.value / [MusicManager shareInfo].player.currentItem.duration.timescale;
    // 获得当前时间
    long long int currentTime = [MusicManager shareInfo].player.currentTime.value / [MusicManager shareInfo].player.currentTime.timescale;
    self.CurrentTimeLabel.text = [NSString stringWithFormat:@"%02lld:%02lld", currentTime / 60, currentTime % 60];
    self.totlaLabel.text = [NSString stringWithFormat:@"%02lld:%02lld", totalTime / 60, totalTime % 60];
    self.slider.maximumValue = totalTime;
    self.slider.minimumValue = 0;
    self.slider.value = currentTime;
    if (self.slider.value == totalTime) {
        [[MusicManager shareInfo] playNext];
        [self reloadDataWithIndex:[MusicManager shareInfo].index];
    }
}
-(void)MusicRuntimeChoose:(UIButton *)btn{
    self.authotId = nil;
    [MusicManager shareInfo].musicArray = self.listArray;
    if (btn.tag == 1000) {
        [_playOrPauseBtn setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
        [[MusicManager shareInfo] playPrevious];
        [self reloadDataWithIndex:[MusicManager shareInfo].index];
    }
    if (btn.tag == 1001) {
        [_playOrPauseBtn setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
        [[MusicManager shareInfo] playNext];
        [self reloadDataWithIndex:[MusicManager shareInfo].index];
    }
    if (btn.tag == 1002) {
        if ([MusicManager shareInfo].isPlay == YES) {
            [btn setImage:[UIImage imageNamed:@"play"] forState:(UIControlStateNormal)];
        }else{
            [btn setImage:[UIImage imageNamed:@"pause"] forState:(UIControlStateNormal)];
        }
        [[MusicManager shareInfo] playAndPause];
    }

}
- (void)reloadDataWithIndex:(NSInteger)index
{
   
    // 寻找model
    OpusListModel *model = [MusicManager shareInfo].musicArray[index];
    [self getPersonDetailVcDataAccordingId:model.opusId];
    // 改变图片 标题 音频
    self.navigationItem.title = model.name;
    // 修改播放歌曲
    [[MusicManager shareInfo] replaceItemWithUrlString:model.filepath];
}
//创建头部视图
-(void)createTableViewUI{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,scaleTopAndBottom(300) + 64, WIDTH, HEIGHT - 64 - scaleTopAndBottom(300)) style:UITableViewStylePlain];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
    }];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    UINib *nib = [UINib nibWithNibName:@"DetailAuthorIntroduceCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"DetailAuthorIntroduceCell"];
    [self.tableView registerClass:[DetailAuthorParticularsIntroduceCell class] forCellReuseIdentifier:@"DetailAuthorParticularsIntroduceCell"];
    UINib *nib2 = [UINib nibWithNibName:@"DetailAuthorHeaderCell" bundle:nil];
    [self.tableView registerNib:nib2 forCellReuseIdentifier:@"DetailAuthorHeaderCell"];
    UINib *nib3 = [UINib nibWithNibName:@"DetailAuthorBottomCell" bundle:nil];
    [self.tableView registerNib:nib3 forCellReuseIdentifier:@"DetailAuthorBottomCell"];
    self.tableView.estimatedRowHeight = 200;
}
#pragma mark -tableView的代理方法

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BigIntellgientModel *model = self.dataArray[indexPath.row];
    if (indexPath.section == 0) {
        static NSString *cellId = @"DetailAuthorHeaderCell";
        DetailAuthorHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        cell.titleLabel.text = model.fielName;
        cell.timeLabel.text = self.totlaLabel.text;
        cell.watchCountLabel.text = model.watchCount;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }else if (indexPath.section == 1){
        static NSString *cellId = @"DetailAuthorIntroduceCell";
        DetailAuthorIntroduceCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        cell.authorNameLabel.text = model.authorName;
        cell.authorDescrLabel.text  = model.auhtorDescrp;
        cell.authorIntroLabel.text = model.auhtorIntroe;
        [cell.authorPicImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",PictureIp,model.authorImagepath]] placeholderImage:[UIImage imageNamed:@""]];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }else if (indexPath.section == 2){
        static NSString *cellId = @"DetailAuthorParticularsIntroduceCell";
        DetailAuthorParticularsIntroduceCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        [cell.contentView addSubview:_webView];
        /* 忽略点击效果 */
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }else{
        static NSString *cellId = @"DetailAuthorBottomCell";
        DetailAuthorBottomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        [cell.commentBtn addTarget:self action:@selector(gotoCommentPage) forControlEvents:UIControlEventTouchUpInside];
        [cell.talkTextfield setAutoAdjust:YES];
        cell.talkTextfield.delegate = self;
        //        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }

   

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return scaleTopAndBottom(70);
    }else if (indexPath.section == 1){
        return UITableViewAutomaticDimension;
    }else if (indexPath.section == 2){
        return _webView.frame.size.height;;
    }else{
        return scaleTopAndBottom(175);
    }

}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0 || section == 3) {
        return 0;
    }else{
        return scaleTopAndBottom(50);
    }

}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor whiteColor];
    if (section == 0) {
        return nil;
    }else if (section == 1){
        return [self createHeaderViewAboutUI:@"作者介绍" AndAddSubviewToFatherview:view];
    }else if (section == 2){
        return [self createHeaderViewAboutUI:@"详情介绍" AndAddSubviewToFatherview:view];
    }else{
        return nil;
    }

}
//创建tableview的头部视图
-(UIView *)createHeaderViewAboutUI:(NSString *)headerTitle AndAddSubviewToFatherview:(UIView *)fatherView{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor yellowColor];
    [fatherView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(fatherView.mas_centerY);
        make.left.equalTo(fatherView.mas_left);
        make.height.mas_equalTo(25);
        make.width.mas_equalTo(scaleLeftAndRight(2));
    }];
    UILabel *lable = [[UILabel alloc] init];
    [fatherView addSubview:lable];
    lable.text = headerTitle;
    [lable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view.mas_right).offset(scaleLeftAndRight(10));
        make.top.equalTo(fatherView.mas_top);
        make.bottom.equalTo(fatherView.mas_bottom);
        make.right.equalTo(fatherView.mas_right).offset(scaleLeftAndRight(-10));
    }];
    return fatherView;
}


#pragma mark - UIScrollViewDelegate和取消区头的停滞效果
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([scrollView isEqual:self.tableView]){
        
    }
    CGFloat sectionHeaderHeight = scaleTopAndBottom(50);
    if (scrollView.contentOffset.y <=sectionHeaderHeight && scrollView.contentOffset.y >=  0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y >=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

//跳转到评论页面
-(void)gotoCommentPage{
    CommentDetailViewController *commentVc = [[CommentDetailViewController alloc] init];
    [self.navigationController pushViewController:commentVc animated:YES];
}
#pragma mark -获取数据
-(void)getPersonDetailVcDataAccordingId:(NSString *)inforId {
    _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _hud.label.text = NSLocalizedString(@"疯狂加载中...", @"HUD loading title");
    [_hud showAnimated:YES];
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        if (self.authotId) {
            self.param = @{@"authorId":inforId,@"type":@"0"};
        }else{
            self.param = @{@"opusId":inforId,@"type":@"0"};
        }
        NSString *url = ServerIp@"/opusApp/detailAll";
        [manager POST:url parameters:_param progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            BigIntellgientModel *model = [BigIntellgientModel modelWithDictionary:jsonDict];
            [self.dataArray addObject:model];
            self.navigationItem.title = model.fielName;
            NSString *videoUrl = model.videoPath;
            NSString *musicStr = [NSString stringWithFormat:@"%@%@",PictureIp,videoUrl];
            NSLog(@"我是ID啊为什么看不见%@",model.FILEID);
            // 修改播放歌曲
            [[MusicManager shareInfo] replaceItemWithUrlString:musicStr];
            NSArray *opulistArra = jsonDict[@"opusFileList"];
            NSDictionary *firstDic = @{@"id":model.FILEID,@"count":model.watchCount,@"niceCount":model.loveCount,@"name":model.fielName,@"file.path":model.videoPath};
            OpusListModel *cataModel = [OpusListModel modelWithDictionary:firstDic];
            [self.listArray addObject:cataModel];
            for (NSDictionary *dic in opulistArra) {
                OpusListModel *listModel = [OpusListModel modelWithDictionary:dic];
                [self.listArray addObject:listModel];
            }
            NSLog(@"这是名字%@",model.fielName);
            dispatch_async(dispatch_get_main_queue(), ^{
//                [_hud hideAnimated:YES];
              
                [self.imageView sd_setImageWithURL:[NSURL URLWithString:model.imagepath] placeholderImage:[UIImage imageNamed:@""]];
                self.senImagePath = model.imagepath;
                _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 1)];
                _webView.delegate = self;
                _webView.scrollView.scrollEnabled = NO;
                NSString *htmlString = [NSString stringWithFormat:@"<html> \n" "<head> \n" "<style type=\"text/css\"> \n" "body {font-size:15px;}\n" "</style> \n" "</head> \n" "<body>" "<script type='text/javascript'>" "window.onload = function(){\n" "var $img = document.getElementsByTagName('img');\n" "for(var p in $img){\n" " $img[p].style.width = '100%%';\n" "$img[p].style.height ='auto'\n" "}\n" "}" "</script>%@" "</body>" "</html>",model.content];
                [self.webView loadHTMLString:htmlString baseURL:nil];
//                [self.tableView reloadData];
            });
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
        }];
        
    });
    
}
#pragma mark - UIWebView Delegate Methods
//-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
//    [_hud hideAnimated:YES];
//    [self createTableViewUI];
//    [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//        CGFloat documentHeight = [result doubleValue];
//        CGRect frame = webView.frame;
//        frame.size.height = documentHeight;
//        webView.frame = frame;
//        NSLog(@"HTML的高度%f",documentHeight);
//    }];
//    [self.tableView reloadData];
//}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [_hud hideAnimated:YES];
    [self createTableViewUI];
    //获取到webview的高度
    CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
    self.webView.frame = CGRectMake(self.webView.frame.origin.x,self.webView.frame.origin.y, WIDTH, height);
    [self.tableView reloadData];
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"webViewDidStartLoad");
}
#pragma mark -textfil的代理方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
#pragma mark -数组延迟加载
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
-(NSMutableArray *)listArray{
    if (_listArray == nil) {
        _listArray = [[NSMutableArray alloc] init];
    }
    return _listArray;
}
#pragma makr -通知的方法执行
-(void)RefreshAndReload:(NSNotification *)infro{
    self.inforId = infro.userInfo[@"opusID"];
}
#pragma mark -列表的选择
-(void)ListCellChoose:(UIButton *)btn{
    FamousListVideoViewController *listvideoVc = [[FamousListVideoViewController alloc] init];
    listvideoVc.dataArray = self.listArray;
    listvideoVc.imagePath = self.senImagePath;
    __weak typeof(self) weakSelf = self;
    listvideoVc.sendIdBlock = ^(NSString * str){
        __strong typeof(self) strongSelf = weakSelf;
        strongSelf.authotId = nil;
        strongSelf.inforId = str;
        [self getPersonDetailVcDataAccordingId:strongSelf.inforId];
    };
    [self.navigationController pushViewController:listvideoVc animated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
